package org.example.forum.controller;

import jakarta.annotation.Nonnull;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.example.forum.common.AppResult;
import org.example.forum.common.ResultCode;
import org.example.forum.config.AppConfig;

import org.example.forum.model.Article;
import org.example.forum.model.User;
import org.example.forum.service.IArticleService;
import org.example.forum.service.IBoradService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.MessageFormat;
import java.util.Date;
import java.util.List;


@Slf4j
@RestController
@RequestMapping("/article")
public class ArticleController {

    @Resource
    private IArticleService articleService;
    @Resource
    private IBoradService boardService;
    @Autowired
    private AppResult appResult;

    @PostMapping("/create")
    public AppResult create(HttpServletRequest request, @Nonnull Long boardId, @Nonnull String title, @Nonnull String content) {
           HttpSession session = request.getSession();
           User user = (User) session.getAttribute(AppConfig.USER_SESSION);
          if(user==null){
              return AppResult.failed(ResultCode.FAILED_UNAUTHORIZED);
          }
           if(user.getState()==1){
               return AppResult.failed(AppResult.failed(ResultCode.FAILED_USER_BANNED));
           }
           Article article = new Article();
           article.setTitle(title);
           article.setContent(content);
           article.setUserId(user.getId());
           article.setBoardId(boardId);
           log.info("boardId:{}",article.getBoardId());
           articleService.create(article);
           Date now = new Date();
           article.setCreateTime(now);
            article.setUpdateTime(now);
           return AppResult.success();

    }
    @GetMapping("/getAllByBoardId")
    public AppResult<List<Article>> getAllByBoardId(@RequestParam(value = "boardId", required = false) Long boardId) {
        List<Article> result = null;
        //根据传的参数返回不同板块的帖⼦列表

        if (boardId == null) {
            result = articleService.selectAll();
            log.info(" 查询所有帖⼦列表");
        } else {
            //参数 i 为空时表⽰指定版本的帖⼦列表
            result = articleService.selectByBoardId(boardId);
            log.info(" 查询版块帖⼦列表, boardId = " + boardId);
        }
        //返回结果
        return AppResult.success(result);
    }
    @GetMapping("/details")
    public AppResult<Article> getDetails(HttpServletRequest request,
                                         @RequestParam(value = "id")  Long id) {
        //获取⽤⼾信息
//当前⽤⼾是否作者

        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //调⽤Service 层获取帖⼦详情
        Article result = articleService.selectDetailById(id);
        if (user.getId() == result.getUserId()) {
            result.setOwn(true);
        }
        //返回结果
        return AppResult.success(result);
    }
    @PostMapping("/modify")
    public AppResult modify(HttpServletRequest request, @Nonnull Long id, @Nonnull String title, @Nonnull String content) {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getState() != 0) {
            log.warn("{}, userId = {}", ResultCode.FAILED_USER_BANNED.toString(), user.getId());
            //返回错误信息
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        Article article = articleService.selectById(id);
        if (article == null) {
            log.warn(" 修改的帖⼦不存在 . articleId = {}", id);
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        //发帖⼈不是当前⽤⼾

        if (article.getUserId() != user.getId()) {
            log.warn(MessageFormat.format("发帖⼈不是当前⽤⼾ . article id = {0}, article user id = {1}, " +
                    "current user id = {2}", article.getId(), article.getUserId(),
                    user.getId()));
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        //帖⼦状态异常

        if (article.getState() != 0 || article.getDeleteState() != 0) {
            log.warn(" 帖⼦状态异常 . articleId = {}, state = {}, delete state = {}", id, article.getState(), article.getDeleteState());
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        //调⽤业务层

        articleService.modify(id, title, content);
        // ⽇志

        log.info(MessageFormat.format(" 帖⼦修改成功 . id = {0}, user id = {1}, 标题 = {2}, 新标题 = {3}",
                id, user.getId(), article.getTitle(), title));
        return  AppResult.success();
    }
    @PostMapping("/thumbsUp")
    public AppResult thumbsUp (HttpServletRequest request,
                               @RequestParam("id") @NonNull Long id) {
        // 校验用户的状态
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        // 判断用户是否被禁言
        if (user.getState() == 1) {
            // 返回结果
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        // 调用Service
        articleService.thumbsUpById(id);
        // 返回结果
        return AppResult.success();
    }
     @PostMapping("/delete")
     public AppResult deleteById (HttpServletRequest request,@RequestParam("id") @NonNull Long id) {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if(user.getState()==1){
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        Article article = articleService.selectById(id);
        if(article.getUserId()==user.getId()){
            return AppResult.failed(ResultCode.FAILED);
        }
        articleService.subOneArticleCountById(id);
        return AppResult.success() ;
     }
    @GetMapping("/getAllByUserId")
    public AppResult<List<Article>> getAllByUserId (HttpServletRequest request ,
                                                    @RequestParam(value = "userId", required = false) Long userId) {
        // 如果UserId为空，那么从session中获取当前登录的用户Id
        if (userId == null) {
            // 获取Session
            HttpSession session = request.getSession(false);
            // 获取User对象
            User user = (User) session.getAttribute(AppConfig.USER_SESSION);
            userId = user.getId();
        }
        // 调用Service
        List<Article> articles = articleService.selectByUserId(userId);
        // 返回结果
        return AppResult.success(articles);
    }

}
